<template>
  <div class="faceCollection1">
    <section class="collect-methods" v-if="headTeacherFlag==true">
      <div class="collect-title">
        <i></i>
        <span>采集对象</span>
      </div>
      <div class="collect-ways clear">
        <el-radio-group v-model="collectWhote">
          <el-radio label="1" border>学生</el-radio>
          <el-radio label="2" border>自己</el-radio>
        </el-radio-group>
      </div>
      <div class="info-form">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" v-show="collectWhote=='1'">
          <el-form-item label="班级" prop="" required>
            <el-radio-group v-model="collectClass" @change="findStudent">
              <el-radio :label="item.id" border v-for="(item,index) of classOptions" :key="index">{{item.rename}}</el-radio>
            </el-radio-group>
            <template v-if="classOptions.length==0">
              <span style="color:#ccc;">暂未绑定班级</span>
            </template>
          </el-form-item>
          <el-form-item label="学生账号" prop="number">
            <template>
              <el-select v-model="ruleForm.id" @change="filterName" placeholder="请选择账号">
                <el-option v-for="item in accountData" :key="item.id" :label="item.number" :value="item.id">
                </el-option>
              </el-select>
            </template>
          </el-form-item>
          <el-form-item label="学生姓名" prop="name">
            <el-input disabled v-model="ruleForm.name"></el-input>
          </el-form-item>
        </el-form>
        <el-form label-width="100px" class="demo-ruleForm" v-show="collectWhote=='2'">
          <el-form-item label="班级">
            <template v-for="(item,index) of classOptions">
              <el-button disabled :key="index"> {{item.rename}}</el-button>
            </template>
            <template v-if="classOptions.length==0">
              <span style="color:#ccc;">暂未绑定班级</span>
            </template>
          </el-form-item>
          <el-form-item label="我的账号">
            <el-input disabled v-model="userInfo.number"></el-input>
          </el-form-item>
          <el-form-item label="真实姓名">
            <el-input disabled v-model="userInfo.name"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </section>

    <section class="collect-photo">
      <div class="collect-title">
        <i></i>
        <span>人脸采集</span>
      </div>
      <div class="collect-tools">
        <!-- <div class="to-shot clear">
          <el-button class="pc-camera-btn fl" @click="shotCollect"><i class="camera-icon"></i><i>使用浏览器启用摄像头采集</i></el-button>
          <div class="tips fl">
            <p>提示说明：</p>
            <p>· 建议使用摄像头采集，数据更精准。</p>
            <p>· 请根据提示进行左右摇头等动作。</p>
          </div>
        </div> -->
        <div class="local-upload clear">
          <div class="choosePic fl">
            <el-button class="localUpload-btn">
              <i class="localUpload-icon"></i>
              <i>上传本地人脸照片</i> <input type="file" accept="image/*" title=" " multiple id="localUploadBtn" @change="localUpload"> </el-button>
            <template>
              <uploader :options="uploadOptions" :autoStart="false" ref="uploader" :file-status-text="statusText" @file-success="fileSuccess" @file-error="fileFail" class="uploader-example">
                <uploader-unsupport></uploader-unsupport>
                <uploader-drop>
                  <uploader-btn :attrs="attrs" :directory="false" :single="false">
                    <i class="change-icon"></i>
                    <i>上传本地人脸照片</i>
                  </uploader-btn>
                </uploader-drop>
              </uploader>
            </template>
          </div>
          <div class="tips fl">
            <p>提示说明：</p>
            <p>· 支持批量上传多张照片；</p>
            <p>· 建议上传多角度人脸照片5到30张。</p>
          </div>
        </div>
      </div>
    </section>
    <section class="view-photo">
      <div class="collect-title">
        <i></i>
        <span>数据显示</span>
      </div>
      <ul class="clear">
        <li class="img-item" v-for="(item,index) in oldPicData" :key="index"><img :src="BASE_URL+item" alt="图片">
          <i class="el-icon-close delPic" @click="deletePhoto(index)"></i>
        </li>
        <!-- <li class="img-item b-red" v-for="item in " :key="item"><img :src="BASE_URL+item" alt="图片"> <i class="el-icon-close delPic"></i></li> -->
        <template v-if="oldPicData.length==0">
          <div class="empty-tips">还没有照片数据哦~</div>
        </template>
      </ul>
    </section>
    <div class="send-info">
      <el-button @click="cancelPicChecked">取消</el-button>
      <el-button type="primary" @click="submitPic" element-loading-text="正在保存..." v-loading.fullscreen.lock="photoListLoading">保存</el-button>
    </div>

    <!-- <el-dialog title="摄像头采集" :visible.sync="viewVisible" width="800px" top="5vh" class="viewdialog dialog-common clear">
      <div class="camera-window">
        <div class="camera">
          ciciiici
        </div>
      </div>
      <div class="startShot" v-if="progressVisible==false">
        <el-button type="primary" @click="startShoot">开始采集</el-button>
        <div class="tips">
          <p>提示：
            <i>点击开始后，请按照进度条文字提示，进行左右摇头等动作。</i>
          </p>
        </div>
      </div>
      <div class="collect-progress" v-if="progressVisible==true">
        <p>"向左稍稍转"</p>
        <el-progress :percentage="70" :stroke-width="8" color="#3BB080"></el-progress>
      </div>
    </el-dialog> -->

    <el-dialog title="本地图片上传" :visible.sync="uploadVisible" width="800px" class="uploaddialog dialog-common" close @close="closeLocalDialog">
      <div class="cropper-area clear">
        <div class="cropper-window fl">
          <vueCropper ref="cropper" :img="option.img" :fixed="option.fixed" :fixedNumber="option.fixedNumber" :outputSize="option.size" :outputType="option.outputType" :info="true" :full="option.full" :canMove="option.canMove" :canMoveBox="option.canMoveBox" :original="option.original" :autoCrop="option.autoCrop" :autoCropWidth="option.autoCropWidth" :autoCropHeight="option.autoCropHeight" :fixedBox="option.fixedBox"></vueCropper>
        </div>
        <div class="cropper-tools fr">
          <div class="cropper-btns">
            <el-button class="continue-btn">
              <i class="continue-icon"></i>
              <i>继续上传</i> <input type="file" accept="image/*" multiple id="continueInput" @change="continuePicture"> </el-button>
            <el-button class="change-btn">
              <i class="change-icon"></i>
              <i>更换图片</i><input type="file" accept="image/*" id="changeInput" :disabled="changePicFlag" @change="changePicture"></el-button>
            <p>提示：请至少上传包含上下左右及正脸等5张照片。</p>
          </div>

          <div class="cropper-icons">
            <i class="del-icon" title="删除" @click="delThumbnail"></i>
            <i class="right-icon" title="裁剪" @click="cutPhoto"></i>
            <!-- <i class="cancel-icon" title="撤销" v-if="cancelvisible" @click="cancelCut"></i> -->
          </div>
        </div>
      </div>

      <!-- swiper -->
      <swiper class="face-carousel" ref="mySwiper" :options="swiperOption">
        <template v-for="(item,index) in thumbnailData">
          <swiper-slide :key="index" :class="activeIndex==index?'active':''"><img :src="item" @click="checkPic(index,item)"></swiper-slide>
        </template>
        <div class="swiper-button-prev" slot="button-prev"></div>
        <div class="swiper-button-next" slot="button-next"></div>
      </swiper>

      <div class="cut-pic-btns">
        <el-button @click="uploadVisible=false">取消</el-button>
        <el-button type="primary" @click="surePhoto">保存</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import { VueCropper } from "vue-cropper";
import 'swiper/dist/css/swiper.css'
import { swiper, swiperSlide } from 'vue-awesome-swiper'

export default {
  components: {
    VueCropper,
    swiper,
    swiperSlide
  },
  data() {
    return {
      userInfo: this.$store.getters.userInfo,
      userRole: this.$store.getters.userInfo.role,
      headTeacherFlag: false, //判断班主任
      // login_id: this.$store.getters.userInfo.id,
      login_id: this.$g.user_id,
      ruleForm: {
        name: "",
        id: ""
      },
      accountData: [],
      collectWhote: "1",
      rules: {
        class: [{ required: true, message: "请选择班级", trigger: "change" }],
        number: [{ required: true, message: "请选择学生账号", trigger: "blur" }]
      },
      viewVisible: false,
      uploadVisible: false,
      classOptions: [], //班级数组
      collectClass: "", //选中的班级
      progressVisible: false, //采集进度条默认不显示
      // 本地图片上传：
      changePicFlag: false,//继续上传按钮是否禁止
      imgFile: "",
      option: {
        img: "",
        outputSize: 1, //剪切后的图片质量（0.1-1）
        full: false, //输出原图比例截图 props名full
        outputType: "png", //输出的照片格式
        canMove: false,
        original: false, //是否显示原始宽高
        canMoveBox: true, //截图框是否能移动
        autoCrop: true, //是否默认显示截图框
        autoCropWidth: 160,
        autoCropHeight: 160,
        minWidth: 100,
        minHeigth: 100,
        fixedBox: false, //截图框是否固定大小
        fixed: true, // 是否开启截图框宽高固定比例
        fixedNumber: [1, 1], //截图框宽高固定比例
        centerBox: false, //截图框是否限制在图片里
        high: true //high //是否根据dpr生成适合屏幕的高清图片
      },

      statusText: {
        success: "上传成功",
        error: "上传出错",
        uploading: "正在上传...",
        paused: "暂停",
        waiting: "等待上传"
      },
      uploadInfo: {
        file_name: "",
        file_path: "",
        file_size: 0
      },
      attrs: {
        accept: ["image/*"]
      },

      uploadOptions: {
        target: this.BASE_URL + "/api/resource/res_upload",
        testChunks: false,
        headers: { Authorization: `Bearer ` + this.$g.access_token },
        // allowDuplicateUploads:true//上传过的，是否可以重新选择
      },
      uploadRetryTimes: 100, //文件最大重传次数
      // picture: [],
      // clearPicFlag:false,
      cancelvisible: false,
      picFileData: [],
      thumbnailData: [], //本地上传功能选中的照片blob
      activeIndex: 0, //选好的照片中，当前选中的那张
      // 撤销前的数据：
      storage_fileList: null,
      storage_thumbnailData: null,
      storage_index: null,
      storage_img: null,

      oldPicData: [],
      target: 0,
      photoListLoading: false,
      // swiper
      swiperOption: {
        slidesPerView: 5,
        spaceBetween: 30,
        slidesPerGroup: 1,
        navigation: {
          nextEl: '.swiper-button-next',
          prevEl: '.swiper-button-prev'
        }
      }
    };
  },
  created() {
    this.getUserClass();
  },
  watch: {
    thumbnailData(newVal, oldVal) {
      //没图片的时候，按钮禁止点击  判断
      if (newVal.length == 0) {
        this.changePicFlag = true;
      } else {
        this.changePicFlag = false;
      }
    },
    collectWhote(newVal, oldVal) {
      if (this.headTeacherFlag == true && newVal == "2") {
        this.getFacePic(this.login_id);
      }
      if (this.headTeacherFlag == true && newVal != oldVal) {
        this.ruleForm.id = "";
        this.ruleForm.name = "";
        this.oldPicData = [];
      }
    },
    "ruleForm.id"(newVal, oldVal) {
      if (this.headTeacherFlag == true && newVal != oldVal) {
        this.oldPicData = [];
      }
    },
    classOptions(newVal, oldVal) {
      //如果只有一个班级的时候，默认选中这个班级
      if (newVal.length == 1) {
        this.collectClass = newVal[0].id;
        this.findStudent();
      }
    }
  },
  methods: {
    //本地上传按钮
    localUpload() {
      // 清空数据
      this.activeIndex = 0;
      this.thumbnailData = [];
      this.picFileData = [];
      //显示弹窗
      this.uploadVisible = true;
      //获取选中的图片
      let imgFiles = document.getElementById("localUploadBtn").files;
      // console.log(imgFiles)
      for (let i = 0; i < imgFiles.length; i++) {
        // 原生方法获取的图片，存起来
        this.picFileData.push(imgFiles[i]);
        //把选中的图片转成blob格式，用于轮播图展示
        this.thumbnailData.push(window.URL.createObjectURL(imgFiles[i]));
      }
      // console.log(this.picFileData)
      //图片裁剪框默认显示轮播图的第一张图片
      this.option.img = this.thumbnailData[0];
    },
    // 本地上传窗口关闭事件
    closeLocalDialog() {
      this.$refs.uploader.uploader.cancel(); //清空上传文件插件里面的数据
    },

    // 继续上传按钮
    continuePicture() {
      //继续上传照片之前已有照片数量，刚好是下次添加图片中第一张的索引：
      let _index = this.thumbnailData.length;
      //获取到的文件
      let imgFiles = document.getElementById("continueInput").files;
      for (var i = 0; i < imgFiles.length; i++) {
        this.picFileData.push(imgFiles[i]);//向图片数组追加文件
        this.thumbnailData.push(window.URL.createObjectURL(imgFiles[i]));//向轮播图数组追加blob格式路径
      }
      // console.log(this.picFileData)
      //让新增的照片中第一张的样式处于选中状态
      this.activeIndex = _index;
      //截图框的照片切换成新增的第一张
      this.option.img = this.thumbnailData[_index];
      //轮播图滑动，到新增的照片中的第一张
      this.$nextTick(function () {
        this.$refs.mySwiper.swiper.slideTo(_index, 1000, false);
      })
    },
    // 替换图片
    changePicture() {
      let inx = this.activeIndex;
      let img = document.getElementById("changeInput").files[0];//选中单张图片
      let imgUrl = window.URL.createObjectURL(img);//图片blob路径
      //替换掉图片数组对应的文件：
      this.picFileData[inx] = img;
      //替换掉轮播图对应的图片：
      this.thumbnailData[inx] = imgUrl;
      //替换掉裁切框的图片：
      this.option.img = imgUrl;
      //轮播图中恢复图片选中状态：
      this.activeIndex = inx;
    },
    // 轮播图的照片选中状态
    checkPic(index, item) {
      // console.log(item)
      this.activeIndex = index;
      this.option.img = item;
    },
    // 删除一张选上的照片
    delThumbnail() {
      if (this.changePicFlag == true) {
        this.$message.error("已经没有照片可删除了");
        return;
      }
      // 删除图片数组里对应的文件
      this.picFileData.splice(this.activeIndex, 1);
      //删除轮播图里对应的照片
      this.thumbnailData.splice(this.activeIndex, 1);
      //删除后，默认选中轮播图第一张
      this.activeIndex = 0;
      //裁切框里面图片更新
      if (this.picFileData.length > 0) {
        this.option.img = window.URL.createObjectURL(this.picFileData[0]);
      } else {
        //这里一定是空的字符串" "，用""不能清空插件裁剪框里的图
        this.option.img = " ";
      }
      // 轮播图滑动到第一张
      this.$nextTick(function () {
        this.$refs.mySwiper.swiper.slideTo(0, 1000, false);
      })
    },

    // 裁剪
    cutPhoto() {
      if (this.changePicFlag == true) {
        this.$message.error("已经没有照片可裁剪了");
        return;
      }
      // 裁剪之前先把对应数据暂存起来，用于撤销裁剪功能
      // this.storage_fileList = this.picFileData;
      // this.storage_thumbnailData = this.thumbnailData;
      // this.storage_index = this.activeIndex;
      // this.storage_img = this.option.img;

      // 裁剪图片
      let inx = this.activeIndex;//当前裁剪图片的索引
      this.$refs.cropper.getCropData(data => {
        // 截图框内的图片更新成裁剪后的
        this.option.img = data;
        // console.log(data)
        // //当前照片裁剪后，uploader里面对应的也更新成裁剪后的
        let modelView = this.dataURLtoFile(
          data,
          this.picFileData[inx].name
        );
        this.picFileData[inx] = modelView;//裁剪成功，替换掉图片数组里对应的文件
        this.thumbnailData[inx] = window.URL.createObjectURL(modelView);//替换轮播图里对应的blob路径
      });
    },
    //将base64转换为文件
    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
    // // 取消当前的裁剪操作
    // cancelCut() {
    //   this.$refs.uploader.uploader.fileList = this.storage_fileList;
    //   this.thumbnailData = this.storage_thumbnailData;
    //   this.activeIndex = this.storage_index;
    //   this.option.img = this.storage_img;
    //   this.cancelvisible = false;
    // },
    // 本地上传的保存按钮
    surePhoto() {
      if (this.picFileData.length > 0) {
        for(let i=0;i<this.picFileData.length;i++){
          //把原生input type=file标签获取到的文件添加到uploader插件
          this.$refs.uploader.uploader.addFile(this.picFileData[i]);
        }
        this.$refs.uploader.uploader.resume();//resume继续上传事件
      } else {
        this.$message.warning("您还未添加图片哦~");
      }
    },
    // 根据身份id,获取该人的图片
    getFacePic(_id) {
      let success = res => {
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].data_path != "") {
            this.oldPicData.push(res.data[i].data_path);
          }
        }
      };
      this.$ajax({
        url: "api/ai/doFaceData",
        method: "get",
        params: {
          user_id: _id,
          data_type: 1 //1是图片
        },
        func: { success: success }
      });
    },
    //图片右上角的删除图标：
    deletePhoto(index) {
      this.oldPicData.splice(index, 1);
    },
    // 取消本地上传选中的图片
    cancelPicChecked() {
      this.oldPicData = [];
      this.getFacePic(this.ruleForm.id);
    },
    // 最终保存图片
    submitPic() {
      if (this.collectWhote == "2" || this.headTeacherFlag == false) {
        this.ruleForm.id = this.$g.user_id;
      }
      let picString = "";
      let _data = this.oldPicData;
      for (var i = 0; i < _data.length; i++) {
        picString += _data[i] + ",";
      }
      if (this.picString == "") {
        this.$message.error("请采集照片再提交哦~");
        return false;
      }
      if (this.ruleForm.id == "") {
        this.$message.error("请选择采集对象再上传~");
        return false;
      }
      this.photoListLoading = true;
      let success = res => {
        this.$message.success("已保存");
        this.getFacePic(this.ruleForm.id);
        this.oldPicData = [];
        this.photoListLoading = false;
      };
      this.$ajax({
        url: "api/ai/doFaceData",
        method: "post",
        data: {
          user_id: this.ruleForm.id,
          pic_str: picString.substring(0, picString.length - 1)
        },
        func: { success: success }
      });
    },
    //获取用户的班级：
    getUserClass() {
      let success = res => {
        this.classOptions = res.data;
        // 如果用户绑定了班级，登录id和自己所处班级数据的base_id是一样的，那用户就是班主任
        if (res.data.length != 0) {
          res.data[0].base_id == this.login_id
            ? (this.headTeacherFlag = true)
            : (this.headTeacherFlag = false);

          //获取自己的数据(学生/普通老师身份)
          if (this.headTeacherFlag == false && this.collectWhote == "1") {
            this.getFacePic(this.login_id);
          }
        }
      };
      this.$ajax({
        url: "api/org/class_userid",
        method: "get",
        params: {
          user_id: this.login_id
        },
        func: { success: success }
      });
    },
    // 根据班级，查找学生
    findStudent() {
      this.accountData = [];
      this.ruleForm.id = "";
      this.ruleForm.name = "";
      let success = res => {
        this.accountData = res.data.data;
      };
      this.$ajax({
        url: "api/org/class_something",
        method: "get",
        params: {
          style: 10,
          classid: this.collectClass,
          page: 1,
          size: 100,
          role_id: 4,
          data_type: 2
        },
        func: { success: success }
      });
    },
    //下拉后，显示对应的学生姓名
    filterName() {
      this.getFacePic(this.ruleForm.id);
      let _id = this.ruleForm.id;
      let _data = this.accountData;
      for (var i = 0; i < _data.length; i++) {
        if (_id == _data[i].id) {
          this.ruleForm.name = _data[i].name;
        }
      }
    },
    // // 摄像头采集显示弹窗按钮：
    // shotCollect() {
    //   this.progressVisible = false;
    //   this.viewVisible = true;
    // },
    // // 摄像头的开始采集按钮
    // startShoot() {
    //   this.progressVisible = true;
    // },
    //插件上传成功的事件
    fileSuccess(rootFile, file, message, chunk) {
      var mess = eval("(" + message + ")");
       mess = handleResponseData(mess);
      if (parseInt(mess.data.status) === 1) {
        this.oldPicData.push(mess.data.file_path);
      }
      if (!this.$refs.uploader.uploader.isUploading()) {
        this.uploadVisible = false;
      }
    },
    //插件上传失败的事件
    fileFail(rootFile, file, message, chunk) {
      var mess = eval("(" + message + ")");
      if (parseInt(mess.error) === 401 && this.uploadRetryTimes > 0) {
        let callbcak = data => {
          this.uploadRetryTimes--;
          this.$refs.uploader.uploader.retry(file);
        };
        this.get_access_token(callbcak);
      } else {
        this.$message.error(mess.msg);
      }
    },
  }
};
</script>
